// # /server/users/UserController.js // 帖子模块 
const fs = require('fs')

import { ObjectId, MongoClient } from 'mongodb'
import YAML from 'yamljs'

import BaseResult from '../lib/BaseResult'

const { mongo } = YAML.parse(fs.readFileSync('./server/config.yaml').toString());
const url = mongo.host;


class PostController {
    // 帖子列表
    async post(ctx) {
        console.log('sss')
        let data = ctx.query;
        return new Promise((resolve) => {
            MongoClient.connect(url, function(err, db) {
                if (err) throw err;
                console.log('数据库已创建');
                var dbo = db.db("blog");
                let where = {};
                if (data.cid) {
                    where["cid"] = data.cid;
                }
                data.size = data.size ? +data.size : 0;
                // console.log('data.size')
                // console.log(data.size)

                dbo.collection("post").find(where).limit(data.size).sort({ "edit_time": -1 }).toArray(function(err, res) {
                    if (err) throw err;
                    //console.log("文档插入成功");
                    //ctx.body = res;
                    ctx.body = new BaseResult(0, 0, res);
                    resolve();
                    db.close();
                });
            });
        })
    }
    async savePost(ctx) {
        
        let data = ctx.request.body;
        // let token = data.token||ctx.query.token||ctx.request.header.token;
        if(!ctx.token){
           /// console.log('sssssssss')
            ctx.body =new BaseResult(9999,null,null);
            return false; 
        }else if(!ctx.session[ctx.token]){
            ctx.body =new BaseResult(9999,'token不正确或以过期',null);
       }
        console.log('ssssdatasssss')
        // 获取帖子前面为摘要
        if (data.content && data.content.lenght > 200) {
            data.digest = data.content.substring(0, 200);
        } else {
            data.digest = data.content;
        }

        return new Promise((resolve) => {
            MongoClient.connect(url, function(err, db) {
                if (err) throw err;
                // console.log('数据库已创建'); 
                var dbo = db.db("blog");

                if (data._id) {
                    let whereStr = { _id: ObjectId(data._id) };
                    dbo.collection("post")
                        .updateOne(whereStr, {
                            $set: {
                                category_id: data.category_id,
                                content: data.content,
                                title: data.title
                            }
                        }, function(err, res) {
                            if (err) throw err;
                            // console.log("文档更新成功");
                            ctx.body = new BaseResult(0, 0, null);
                            resolve();
                            db.close();
                        });
                } else {
                    data.userid = ctx.session[ctx.token]&&ctx.session[ctx.token].userid;
                    data.userName = ctx.session[ctx.token]&&ctx.session[ctx.token].userName;
                    //阅读数
                    data.read = 0;
                    data.create_time = (+new Date());
                    data.edit_time = (+new Date());
                    dbo.collection("post")
                        .insertOne(data).then((res, l) => {
                            // if (err) throw err;
                            // console.log("文档插入成功");
                            // ctx.body = "文档插入成功";
                            ctx.body = new BaseResult(0, 0, data);
                            resolve();
                            db.close();
                        });
                }

            });
        })
    }
    async findPost(ctx) {
        let data = ctx.query;
        return new Promise((resolve) => {
            MongoClient.connect(url, function(err, db) {
                if (err) throw err;
                console.log('数据库已创建');
                var dbo = db.db("blog");
                // var myobj = { name: "菜鸟教程", url: "www.runoob" };
                dbo.collection("post").find({
                    _id: ObjectId(data.id)
                }).toArray(function(err, res) {
                    if (err) throw err;
                    ctx.body = new BaseResult(0, 0, res[0]);
                    console.log(ctx.session)
                   let read =  ctx.session['read'+data.id];
                    //设置阅读
                    if (!read) {
                        ctx.session['read'+data.id] = true;
                        // console.log(res[0])
                        let read = res[0].read;
                        //console.log(read)
                            // console.log(++read++)
                        let whereStr = { _id: ObjectId(data.id) };
                       // console.log(whereStr)
                        dbo.collection("post")
                            .updateOne(whereStr, {
                                $set: {
                                    read: ++read
                                }
                            }, function(params, k) {
                                console.log('params  ', params)

                            })
                            // }

                    }
                    resolve();
                    db.close();
                });

            });
        })
    }
}
// exports.post = new PostController();
export default new PostController();